#include "stdafx.h"
#include "HeadTracker.h"

using namespace cv;
HeadTracker::HeadTracker(void)
{
	key = 0;  
    frame = 0;

}


HeadTracker::~HeadTracker(void)
{
}

int HeadTracker::init()
{

	// Initialize capturing live feed from camera  
    capture = cvCaptureFromCAM(1);
	
	// Get the frames per second  
    int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS );    
  
    if( !capture )  
    {  
        printf( "Could not initialize capturing...\n" );  
        return -1;  
    }
	
	return 0;
}

IplImage* HeadTracker::GetThresholdedImageHSV( IplImage* img )  
{  
    // Create an HSV format image from image passed  
    IplImage* imgHSV = cvCreateImage( cvGetSize( img ), 8, 3 );     
  
    cvCvtColor( img, imgHSV, CV_BGR2HSV );  
  
    // Create binary thresholded image acc. to max/min HSV ranges  
    // For detecting Green object - HSV mode  
    IplImage* imgThresh = cvCreateImage( cvGetSize( img ), 8, 1 );             
  
    cvInRangeS( imgHSV, cvScalar( minH, minS, minV  ), cvScalar( maxH, maxS, maxV ), imgThresh );  
  
    // Tidy up and return thresholded image  
    cvReleaseImage( &imgHSV );  
    return imgThresh;  
}

void HeadTracker::set_Max_HSV(int H, int S, int V)
{
	maxH = H; maxS = S; maxV = V;
}

void HeadTracker::set_Min_HSV(int H, int S, int V)
{
	minH = H; minS = S; minV = V;
}

void HeadTracker::set_thresh_size(int thresh_size)
{
	min_thresh_size = thresh_size;
}

CvRect HeadTracker::get_rectangle()
{
		frame = cvQueryFrame( capture );  
        // If we couldn't grab a frame... quit  
		if(!frame){}        
  
        // Get object's thresholded image (blue = white, rest = black)  
        IplImage* imgThresh = GetThresholdedImageHSV( frame );        
  
        // Detect the white blobs from the black background  
        blobs = CBlobResult( imgThresh, NULL, 0 );    
  
        // Exclude white blobs smaller than the given value (10)    
        // The bigger the last parameter, the bigger the blobs need    
        // to be for inclusion    
        blobs.Filter( blobs, B_EXCLUDE, CBlobGetArea(), B_LESS, min_thresh_size );           
  
        int num_blobs = blobs.GetNumBlobs();  
  
        for ( int i = 0; i < num_blobs; i++ )    
        {                 
            currentBlob = blobs.GetBlob( i );               
            cvRect = currentBlob->GetBoundingBox();
		}
		cvWaitKey(1);
		return cvRect;
}